package com.boe.csb.core.service.api;

import java.util.Arrays;
import java.util.List;

import com.boe.csb.core.common.status.UserPicType;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.status.PublishStatusEnum;
import com.boe.csb.core.common.utils.PropertyUtils;
import com.boe.csb.core.dao.BoeApiInfoCriteria;
import com.boe.csb.core.dao.BoeApiInfoMapper;
import com.boe.csb.core.entity.po.BoeApiInfo;

/**
 * Created by tianxiang.luo on 16/11/24.
 */
@Service("boeApiInfoService")
public class BoeApiInfoService {

    private static final Logger logger = LoggerFactory.getLogger(BoeApiInfoService.class);

    private static int IS_RECOMMEND = 1;

    private static int IS_NOT_RECOMMEND = 0;

    private static int RECOMMAND_LIMIT = 6;//推荐限制数量

    private static String javaSdkName;

    private static String phpSdkName;

    private static String shellSdkName;

    private static String cSharpSdkName;

    private static String pythonSdkName;

    private static String ocSdkName;

    @Autowired
    private BoeApiInfoMapper boeApiInfoMapper;
    @Autowired
    private static final List<String> API_CAN_READ = Arrays.asList(PublishStatusEnum.ACTIVE.getStatus(), PublishStatusEnum.STOP.getStatus());


    static {
        javaSdkName = PropertyUtils.getProperty("java.sdk.file.name");
        phpSdkName = PropertyUtils.getProperty("php.sdk.file.name");
        shellSdkName = PropertyUtils.getProperty("shell.sdk.file.name");
        cSharpSdkName = PropertyUtils.getProperty("csharp.sdk.file.name");
        pythonSdkName = PropertyUtils.getProperty("python.sdk.file.name");
        ocSdkName = PropertyUtils.getProperty("oc.sdk.file.name");
    }

    /**
     * 根据 搜索栏模糊查询 页数
     */
    public List<BoeApiInfo> findBoeApiInfo(String query, Integer pageNum, Integer limit) {
        if (StringUtils.isEmpty(query)) {
            return null;
        }
        List<BoeApiInfo> list  = boeApiInfoMapper.selectByDesc("%" + query + "%", (pageNum - 1) * limit, limit);
        for(BoeApiInfo info:list){
            info.setApiPic(getImgPathByService(info));
        }
        return list;
    }

    /**
     * 数据条数
     */
    public Integer findBoeApiInfoCount(String query) {
        if (StringUtils.isEmpty(query)) {
            return 0;
        }
        return boeApiInfoMapper.countByDesc("%" + query + "%");
    }

    /**
     * 获取精品服务
     *
     * @param pageNum
     * @param limit
     * @return
     */
    public List<BoeApiInfo> queryRecommendBoeApiList(Integer pageNum, Integer limit) {
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andIsRecommendEqualTo((byte) IS_RECOMMEND);
        List<BoeApiInfo> infos =  boeApiInfoMapper.selectByExampleWithRowbounds(criteria, new RowBounds((pageNum - 1) * limit, limit));
        for(BoeApiInfo info:infos){
            info.setApiPic(getImgPathByService(info));
        }
        return infos;
    }

    public CSBErrorCode addRecommend(long apiId) {

        //判断服务是否存在
        BoeApiInfoCriteria existsCriteria = new BoeApiInfoCriteria();
        existsCriteria.createCriteria().andCsbApiIdEqualTo(apiId);
        List<BoeApiInfo> boeApiInfos = boeApiInfoMapper.selectByExample(existsCriteria);
        if (boeApiInfos.size() < 1) {
            return CSBErrorCode.ADD_RECOMMEND_NOT_EXISTS;
        }
        if (!(PublishStatusEnum.ACTIVE.getStatus().equals(boeApiInfos.get(0).getApiStatus()) ||
                PublishStatusEnum.STOP.getStatus().equals(boeApiInfos.get(0).getApiStatus()))) {
            return CSBErrorCode.SERVICE_STATUS_FORBIDDEN;
        }

        //判断推荐服务数量是否超过设定上限
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andIsRecommendEqualTo((byte) IS_RECOMMEND);
        long count = boeApiInfoMapper.countByExample(criteria);
        if (count >= RECOMMAND_LIMIT) {
            return CSBErrorCode.ADD_RECOMMEND_OVER_LIMIT;
        }

        BoeApiInfo updateApi = new BoeApiInfo();
        updateApi.setIsRecommend((byte) IS_RECOMMEND);

        BoeApiInfoCriteria updateBy = new BoeApiInfoCriteria();
        updateBy.createCriteria().andCsbApiIdEqualTo(apiId);

        int rst = boeApiInfoMapper.updateByExampleSelective(updateApi, updateBy);
        if (rst < 1) {
            logger.error("add recommend fail, please check.");
            return CSBErrorCode.ADD_RECOMMEND_ERR;
        }

        return CSBErrorCode.SUCCESS;
    }

    public CSBErrorCode delRecommand(long apiId) {

        BoeApiInfo updateApi = new BoeApiInfo();
        updateApi.setIsRecommend((byte) IS_NOT_RECOMMEND);

        BoeApiInfoCriteria updateBy = new BoeApiInfoCriteria();
        updateBy.createCriteria().andCsbApiIdEqualTo(apiId);

        int rst = boeApiInfoMapper.updateByExampleSelective(updateApi, updateBy);
        if (rst < 1) {
            logger.error("delete recommend fail, please check.");
            return CSBErrorCode.ADD_RECOMMEND_ERR;
        }

        return CSBErrorCode.SUCCESS;
    }

    /**
     * 根据二级类目id 页数
     */
    public List<BoeApiInfo> queryBoeApiInfoList(Long categoryId, Integer pageNum, Integer limit) {
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCategoryIdEqualTo(categoryId).andApiStatusIn(API_CAN_READ);
        List<BoeApiInfo> infos =  boeApiInfoMapper.selectByExampleWithRowbounds(criteria, new RowBounds((pageNum - 1) * limit, limit));
        for(BoeApiInfo info:infos){
            info.setApiPic(getImgPathByService(info));
        }
        return infos;
    }


    /**
     * 查询二级类目的数据
     */
    public Long countSecondList(Long categoryId) {
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCategoryIdEqualTo(categoryId).andApiStatusIn(API_CAN_READ);
        return boeApiInfoMapper.countByExample(criteria);
    }

    /**
     * 查询服务
     */
    public BoeApiInfo queryBoeApiInfo(Long serviceId) {
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCsbApiIdEqualTo(serviceId);
        List<BoeApiInfo> boeApiInfoList = boeApiInfoMapper.selectByExample(criteria);
        if (!CollectionUtils.isEmpty(boeApiInfoList)) {
            boeApiInfoList.get(0).setApiPic(getImgPathByService(boeApiInfoList.get(0)));
            return boeApiInfoList.get(0);
        }
        return null;
    }

    /**
     * 更新api状态
     *
     * @param serviceIdList
     * @param status
     */
    public void updateApiStatus(List<Long> serviceIdList, String status) {
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCsbApiIdIn(serviceIdList);
        BoeApiInfo info = new BoeApiInfo();
        info.setApiStatus(status);
        boeApiInfoMapper.updateByExampleSelective(info, criteria);
    }

    public String getSdkName(String type) {
        if ("java".equalsIgnoreCase(type)) {
            return javaSdkName;
        } else if ("php".equalsIgnoreCase(type)) {
            return phpSdkName;
        } else if("shell".equalsIgnoreCase(type)){
            return shellSdkName;
        } else if("csharp".equalsIgnoreCase(type)){
            return cSharpSdkName;
        } else if("python".equalsIgnoreCase(type)){
            return pythonSdkName;
        }else if("oc".equalsIgnoreCase(type)){
            return ocSdkName;
        }

        return null;
    }


    public String getImgPathByServiceId(Long serviceId){
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCsbApiIdEqualTo(serviceId);
        List<BoeApiInfo> infos = boeApiInfoMapper.selectByExample(criteria);
        if(!CollectionUtils.isEmpty(infos)){
            BoeApiInfo info = infos.get(0);
            return "/api/user/getImg?userId="+info.getUserId()+"&type="+UserPicType.servicePic.name()+"&csbApiId="+serviceId;
        }
        return null;
    }

    public String getImgPathByService(BoeApiInfo info){
        return "/api/user/getImg?userId="+info.getUserId()+"&type="+UserPicType.servicePic.name()+"&csbApiId="+info.getCsbApiId();
    }

    public String getApiServerNameById(Long serviceId){
        BoeApiInfoCriteria criteria = new BoeApiInfoCriteria();
        criteria.createCriteria().andCsbApiIdEqualTo(serviceId);
        List<BoeApiInfo> infos = boeApiInfoMapper.selectByExample(criteria);
        if(!CollectionUtils.isEmpty(infos)){
            BoeApiInfo info = infos.get(0);
            return info.getApiName();
        }
        return "";
    }
}
